package com.snsoft.util;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.mchange.v2.c3p0.ComboPooledDataSource;

/**
 * 
 * @author 慎伟康
 * 
 * @date 2017年9月17日 上午7:11:22
 * 
 * @Description TODO
 *		jdbc工具类
 *    jar依赖：
 *    mysql-connector-java-5.1.7-bin.jar
 *    c3p0-0.9.1.2.jar
 */
public class JdbcUtils {
	
    private static ComboPooledDataSource dataSource;
    private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
	
	static{
		dataSource = new ComboPooledDataSource();
	}
	
	/**
	 * 取得数据源
	 * @return
	 */
	public static ComboPooledDataSource getDataSource() {
		return dataSource;
	}
	
	/**
	 * 取得连接
	 * @return
	 * @throws SQLException
	 */
	public static Connection getMySQlConnection() throws SQLException{
		//返回当前线程绑定的连接
		Connection conn = tl.get();
		
		//如果线程未绑定连接对象
		if(conn == null){
			//取得连接池的一个空闲连接对象
			conn = dataSource.getConnection();
			//绑定到当前线程
			tl.set(conn);
		}
		return conn;
	}
	
	/**
	 * 释放资源
	 * @param conn
	 * @throws SQLException
	 */
	public static void close(Connection conn){
		if(conn != null){
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			conn = null;
		}
	}
	public static void close(Statement stat){
		if(stat != null){
			try {
				stat.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			stat = null;
		}
	}
	public static void close(ResultSet rs){
		if(rs != null){
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			rs = null;
		}
	}
	public static void close(Connection conn, Statement stat, ResultSet rs){
		close(rs);
		close(stat);
		close(conn);
	}
	public static void close(Connection conn, Statement stat){
		close(stat);
		close(conn);
	}
	
	/**
	 * 开启事务
	 * @throws SQLException 
	 */
	public static void startTransaction() throws SQLException{
		Connection conn = getMySQlConnection();
		if(conn != null){
			conn.setAutoCommit(false);
		}
	}
	
	/**
	 * 事务回滚
	 * @throws SQLException 
	 */
	public static void rollback() throws SQLException{
		Connection conn = getMySQlConnection();
        if(conn != null){
        	conn.rollback();
		}
	}
	
	/**
	 * 事务提交
	 * @throws SQLException 
	 */
	public static void commit() throws SQLException{
		Connection conn = getMySQlConnection();
		if(conn != null){
			conn.commit();
		}
	}
	
	/**
	 * 解除当前线程的绑定，关闭连接
	 * @throws SQLException
	 */
	public static void closeConnection() throws SQLException{
		Connection conn = getMySQlConnection();
		if(conn != null){
			conn.close();
			tl.remove();
		}
	}
	
}

